package com.sky.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersCancelDTO;
import com.sky.dto.OrdersConfirmDTO;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersRejectionDTO;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.AdminOrderMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.result.PageResult;
import com.sky.service.AdminOrderService;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class AdminOrderServiceImpl implements AdminOrderService {

    @Autowired
    private AdminOrderMapper adminOrderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 订单搜索
     *
     * @param ordersPageQueryDTO
     * @return {@link PageResult}
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        //todo 1.开启
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        // todo 2.原始查询
        List<Orders> ordersList = adminOrderMapper.selectPage(ordersPageQueryDTO);
        /*ordersList.forEach(orders -> {
            String orderDishes = getDishString(orders);
            orders.setOrderDishes(orderDishes);
        });*/
        //todo 3.数据转换
        PageInfo<Orders> pageInfo = PageInfo.of(ordersList);
        List<Orders> orders = pageInfo.getList();
        List<OrderVO> orderVOList = orders.stream().map(orders1 -> {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders1, orderVO);
            String orderDishes = getDishString(orders1);
            orderVO.setOrderDishes(orderDishes);
            return orderVO;
        }).collect(Collectors.toList());
        //todo 4.封装并返回
        PageResult pageResult = new PageResult();
        pageResult.setTotal(pageInfo.getTotal());
        pageResult.setRecords(orderVOList);
        return pageResult;
    }


    /**
     * 各个状态的订单数量统计
     *
     * @return {@link OrderStatisticsVO}
     */
    @Override
    public OrderStatisticsVO statistics() {
        //待接单数量
        Integer toBeConfirmed = adminOrderMapper.selectByStatus(Orders.TO_BE_CONFIRMED);
        //待派送数量
        Integer confirmed = adminOrderMapper.selectByStatus(Orders.CONFIRMED);
        //派送中数量
        Integer deliveryInProgress = adminOrderMapper.selectByStatus(Orders.DELIVERY_IN_PROGRESS);

        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    /**
     *查询订单详情
     *
     * @param id
     * @return {@link OrderVO}
     */
    @Override
    public OrderVO details(Long id) {
        OrderVO orderVO = new OrderVO();

        //todo 1.获取orderDishes和orderDetailList
        Orders orders = orderMapper.selectById(id);
        String orderDishes = getDishString(orders);
        List<OrderDetail> orderDetailList = orderDetailMapper.selectByOrderId(id);

        //todo 2.封装返回
        BeanUtils.copyProperties(orders,orderVO);
        orderVO.setOrderDishes(orderDishes);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    /**
     * 接单
     *
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = new Orders();
        orders.setId(ordersConfirmDTO.getId());
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.update(orders);
    }

    /**
     * 拒单
     *
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        //todo 1.只有在待接单状态下可以拒单 --> status = 2
        Orders orders = orderMapper.selectById(ordersRejectionDTO.getId());
        if (orders.getStatus() != 2){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // todo 2.退款操作

        //todo 3.修改订单状态,支付状态,订单拒绝原因,订单取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setPayStatus(Orders.REFUND);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());

        // todo 4.根据订单id修改订单
        orderMapper.update(orders);
    }

    /**
     * 取消订单
     *
     * @param ordersCancelDTO
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        //todo 1.获取订单,只有在status 1,3,4时可以取消
        Orders orders = orderMapper.selectById(ordersCancelDTO.getId());
        if (orders.getStatus() != 1 && orders.getStatus() != 3 && orders.getStatus() != 4){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // todo 2.退款操作

        //todo 3.修改订单状态,支付状态,订单取消原因,订单取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setPayStatus(Orders.REFUND);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());

        // todo 4.根据订单id修改订单
        orderMapper.update(orders);
    }

    /**
     * 派送订单
     *
     * @param id
     */
    @Override
    public void delivery(Long id) {
        //todo 1.只有在待派送(3)的状态下可以派送
        Orders orders = orderMapper.selectById(id);
        if (orders.getStatus() != 3){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //todo 2.更改订单状态
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(orders);
    }

    /**
     * 完成订单
     *
     * @param id
     */
    @Override
    public void complete(Long id) {
        //todo 1.只有派送中(4)可以进行完成操作
        Orders orders = orderMapper.selectById(id);
        if (orders.getStatus() != 4 || Objects.isNull(orders)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //todo 2.更改订单状态为已完成,送达时间
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 订单包含的菜品，以字符串形式展示
     *
     * @param orders
     * @return {@link String}
     */
    private String getDishString(Orders orders) {
        List<OrderDetail> orderDetailList = orderDetailMapper.selectByOrderId(orders.getId());
        List<String> orderDishList = orderDetailList.stream().map(orderDetail -> {
            String orderDish = orderDetail.getName() + "*" + orderDetail.getNumber();
            return orderDish;
        }).collect(Collectors.toList());
        String orderDishes = StringUtils.join(orderDishList, ",");
        return orderDishes;
    }
}
